6 typedef int T
; /* type of item to be sorted */
7 typedef int tblIndex
; /* type of subscript */
9 #define compGT(a,b) (a > b)
10 #define compLT(a,b) (a < b)
12 void sortByInsertion(T
*x
, tblIndex lb
, tblIndex ub
) {
15 for (i
= lb
+ 1; i
<= ub
; i
++) {
18 /* shift down until insertion point found */
19 for (j
= i
-1; j
>= 0 && compGT(x
[j
], t
); j
--)
27 tblIndex
partition(T
*x
, tblIndex lb
, tblIndex ub
) {
30 double pivot
= x
[(lb
+ub
)/2];
32 /* work from both ends, swapping to keep */
33 /* values less than pivot to the left, and */
34 /* values greater than pivot to the right */
40 while (compGT(x
[--j
], pivot
));
41 while (compLT(x
[++i
], pivot
));
53 void quickSort(T
*x
, tblIndex lb
, tblIndex ub
) {
57 m
= partition(x
, lb
, ub
);
59 quickSort(x
, m
+ 1, ub
);
62 void quickSortImproved(T
*x
, tblIndex lb
, tblIndex ub
) {
66 /* quickly sort short lists */
68 sortByInsertion(x
, lb
, ub
);
72 m
= partition(x
, lb
, ub
);
74 /* eliminate tail recursion and */
75 /* sort the smallest partition first */
76 /* to minimize stack requirements */
77 if (m
- lb
<= ub
- m
) {
78 quickSortImproved(x
, lb
, m
);
81 quickSortImproved(x
, m
+ 1, ub
);
87 void fill(T
*a
, tblIndex lb
, tblIndex ub
) {
90 for (i
= lb
; i
<= ub
; i
++) a
[i
] = rand();
93 int main(int argc
, char *argv
[]) {
94 tblIndex maxnum
, lb
, ub
;
106 maxnum
= atoi(argv
[1]);
107 lb
= 0; ub
= maxnum
- 1;
108 if ((a
= malloc(maxnum
* sizeof(T
))) == 0) {
109 fprintf (stderr
, "insufficient memory (a)\n");
114 quickSortImproved(a
, lb
, ub
);